package pl.vanta.utils.commons.managers;

import java.util.Map;
import java.util.WeakHashMap;

public abstract class AbstractManager<K, V>
{
	private Map<K, V>				resources;
	private AbstractManager<K, V>	parent;

	protected AbstractManager()
	{
		this(null);
	}

	protected AbstractManager(AbstractManager<K, V> parent)
	{
		this.parent = parent;
		this.resources = new WeakHashMap<K, V>();
	}

	public void clear()
	{
		this.resources.clear();
	}

	public V get(K key)
	{
		V resource = this.resources.get(key);

		if (resource == null && this.parent != null)
		{
			resource = this.parent.get(key);
		}

		if (resource == null)
		{
			resource = resourceNotFound(key);
			put(key, resource);
		}

		return resource;
	}

	protected synchronized void put(K key, V value)
	{
		this.resources.put(key, value);
	}

	public abstract V resourceNotFound(K key);
}